import importlib
import inspect
from tornado.util import import_object #https://www.osgeo.cn/tornado/util.html#tornado.util.import_object
from tornado.web import url

from utils import iter_all_modules

class HandlerDecorate:
    
    def __init__(self,path) -> None:
        self.__url_path__ = path

    def __call__(self,cls):
        cls.__url_path__ = self.__url_path__
        return cls
    
class OpenHandler:
    # 路由的处理类
    def __init__(self, source_libs):
        # 传递目录名，用于获取目录下所有使用装饰器的类
        self.source_libs = source_libs
        # 存储路由的列表
        self._handler_libs_ = None

    def get_handlers(self):
        self._handler_libs_ = []
        for _sys in self.source_libs:
            # 遍历引入模块
            _app = importlib.import_module(_sys)

            for _module in iter_all_modules(_app.__path__[0],_app.__name__ + ".","handler"):
                self._handler_libs_ + [
                    dict(
                        path=_cls.__url_path__, # 路径
                        obj=_cls.__module__ + "." + _cls.__name__, # 路径对应的类
                        index=_cls.__url_path_index__ # 用于排序的key
                    )
                    # 过滤出是类的属性，并且含有__url_path__属性的对象
                    for _n, _cls in inspect.getmembers(_module, inspect.isclass) if hasattr(_cls, '__url_path__')
                ]
        # 按照index排序
        self._handler_libs_.sort(key=lambda x: x['index'])

        _result = []
        for _handler_lib in self._handler_libs_:
            # 遍历生成tornado的路由对象
            _path = _handler_lib.get("path")
            _result.append(url(_path,import_object(_handler_lib.get("obj"))))
            pass

        # 所有的路由列表
        return _result
